define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'inventory/procure/index' + location.search,
                    add_url: 'inventory/procure/add',
                    edit_url: 'inventory/procure/edit',
                    del_url: 'inventory/procure/del',
                    multi_url: 'inventory/procure/multi',
                    import_url: 'inventory/procure/import',
                    table: 'procure',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                //search:false,
                fixedColumns: true,
                showToggle:false,
                fixedRightNumber: 2,
                columns: [
                    [
                        {checkbox: true},
                        {field: 'type', title: __('Type'),searchList: {"0":'采购订单',"1":'MES入库',"2":'生产任务'}, formatter: Table.api.formatter.flag },
                     //   {field: 'order_code', title: __('Order_code'), operate: 'LIKE'},
                        {field: 'warehousing_code', title: __('Warehousing_code'), operate: 'LIKE'},
                        {field: 'order_date', title: __('Order_date'), operate:'RANGE', addclass:'datetimerange', autocomplete:false},
                        {field: 'factory_name', title: __('Factory_name'), operate: 'LIKE'},
                        {field: 'row_id', title: __('Row_id'), operate: 'LIKE'},
                        {field: 'name', title:__('Name'),operate: 'LIKE'},
                        {field: 'inventory_number', title:__('Inventory_number'),operate: 'LIKE'},
                        {field: 'specification', title:__('Specification'),operate: 'LIKE'},
                        {field: 'unit', title:__('Unit'),operate: 'LIKE'},
                        {field: 'quantity', title: __('Quantity'), operate:'BETWEEN'},
                        
                        //{field: 'warehousing_date', title: __('Warehousing_date'), operate:'RANGE', addclass:'datetimerange', autocomplete:false},
                        //{field: 'factory_code', title: __('Factory_code'), operate: 'LIKE'},
                        
                        
                        //{field: 'attributes', title:"物料属性",operate: 'LIKE'},
                        
                        //{field: 'unit_price', title: __('Unit_price'), operate:'BETWEEN'},
                        //{field: 'total_price', title: __('Total_price'), operate:'BETWEEN'},
                        {field: 'warehousing_quantity', title: __('Warehousing_quantity'), operate:'BETWEEN'},
                        {field: 'no_quantity', title: __('No_quantity'), operate:'BETWEEN'},
                        
                        //{field: 'sh_time', title: "审核时间", operate:'RANGE', addclass:'datetimerange', autocomplete:false},
                        {field: 'warehouse_name', title: __('Warehouse_id'), operate: 'LIKE'},
                        {field: 'shelves_name', title: __('Shelves_id'), operate: 'LIKE'},
                        {field: 'lastest_warehouse_name', title: __('Lastest_warehouse_id'), operate: 'LIKE'},
                        {field: 'lastest_shelves_name', title: __('Lastest_shelves_id'), operate: 'LIKE'},
                        {field: 'remark', title: __('Remark'), operate: 'LIKE'},
                        {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false,operate:false},
                        //{field: 'updatetime', title: __('Updatetime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false},
                        //{field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate}
                        {field: 'status', title: '状态', searchList: {"0":'关闭',"1":'开启'}, formatter: Table.api.formatter.normal},
                        {field: 'operate', title: __('Operate'), table: table,
                            buttons: [
                                {name: 'detail', text: '详情', title: '详情', icon: 'fa fa-list', classname: 'btn btn-xs btn-primary btn-dialog',url:'inventory/procure/edit?flag=print&single=0',}
                            ],
                            events: Table.api.events.operate,
                            formatter:function (value, row, index) {
                                var that = $.extend({},this);
                                var table = $(this.table).clone(true);
                                //后端传之判断是否有编辑、删除操作权限
                                $(table).data('operate-edit',null);
                                $(table).data('operate-del',null);
                                that.table = table;
                                return Table.api.formatter.operate.call(that,value,row,index);
                            }
                        }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);

            $('.btn-danger').on('click',function(){
                Toastr.info("数据同步中请稍后....");
                $.post('inventory/procure/getData',function(e){
                       if(e.code==1){
                         Toastr.success(e.msg);
                         table.bootstrapTable('refresh');
                       }else{
                         Toastr.error(e.msg);
                       }
                    })
            })
            
            // $('#print-btn').click(function(){
            // 	let list =  table.bootstrapTable('getSelections');
            // 	if(list.length==0){
            // 		return Toastr.error("请先选择要打印的记录");   
            // 	}
            // 	let ids_arr = []
            // 	for(let i=0;i<list.length;i++){
            // 		ids_arr.push(list[i].inv_id)
            // 	}
            //     Fast.api.open('information/inventory/print?inventory_id='+ids_arr.join(','),'打印物料信息');
            // })
            $('#print-btn').click(function(){
                let list =  table.bootstrapTable('getSelections');
                if(list.length==0){
                    return Toastr.error("请先选择要打印的记录");   
                }
                let ids_arr = []
                let cBatch_arr = []
                var date = new Date();
                var today = formatDate(date);
                for(let i=0;i<list.length;i++){
                    ids_arr.push(list[i].inv_id)
                    if(!list[i].cBatch){
                        list[i].cBatch = today
                    }
                    cBatch_arr.push(list[i].cBatch)
                }
                Fast.api.open('information/inventory/print?inventory_id='+ids_arr.join(',')+'&cBatch='+cBatch_arr.join(','),'打印物料信息');
            })
            
            //入库分析清单打印
            $(document).on("click", ".btn-print", function (e, obj) {
            	let ids =  Controller.api.selectedids(table);
            	if(!ids.length){
            		Toastr.error("请选择要打印的入库分析清单");
            		return
            	}
            	/*if(ids.length!=1){
            		Toastr.error("请选择要一条记录进行打印");
            		return
            	}*/
            	let ids_arr = []
            	for(let i=0;i<ids.length;i++){
            		if(i>0&&ids[i].warehousing_code!=ids[i-1].warehousing_code){
            			Toastr.error("请选择同一张采购订单");
            			return 
            		}
            		ids_arr.push(ids[i].id)
            	}
            	Backend.api.open("inventory/procure/edit?flag=print&single=1&ids="+ids_arr.join(','),"入库任务分析打印") //,{area:["100%", "100%"]}
            })
            
            //定时器,每60秒刷新一次
            var timer = setInterval(function() {
            	$("a.btn-refresh").trigger("click");
            }, 60*1000);
            
            $("#btn-stop-refresh").on('click',function(){
            	if($("#btn-stop-refresh").html()=='停止刷新'){
            		$("#btn-stop-refresh").html('开启刷新')
            		clearInterval(timer)
            	}else{
            		$("#btn-stop-refresh").html('停止刷新')
            	    timer = setInterval(function() {
                     	$("a.btn-refresh").trigger("click");
                    }, 60*1000);
            	}
            })
        },
        mesindex: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'inventory/procure/mesindex' + location.search,
                    del_url: 'inventory/procure/del',
                    table: 'procure',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                //search:false,
                fixedColumns: true,
                showToggle:false,
                fixedRightNumber: 1,
                columns: [
                    [
                        {checkbox: true},
                        {field: 'source_code', title: __('生产任务单'), operate: 'LIKE'},
                        {field: 'warehousing_code', title: __('Warehousing_code'), operate: 'LIKE'},
                        {field: 'order_date', title: __('Order_date'), operate:'RANGE', addclass:'datetimerange', autocomplete:false},
                        {field: 'factory_name', title: __('车间'), operate: 'LIKE'},
                        {field: 'row_id', title: __('Row_id'), operate: 'LIKE'},
                        {field: 'name', title:__('Name'),operate: 'LIKE'},
                        {field: 'inventory_number', title:__('Inventory_number'),operate: 'LIKE'},
                        {field: 'specification', title:__('Specification'),operate: 'LIKE'},
                        {field: 'unit', title:__('基本单位'),operate: 'LIKE'},
                        {field: 'cBatch', title:__('批次'),operate: 'LIKE'},
                        {field: 'quantity', title: __('基本数量'), operate:'BETWEEN'},
                        {field: 'store_unit', title:__('常用单位'),operate: 'LIKE'},
                        {field: 'store_quantity', title: __('常用数量'), operate:'BETWEEN'},
                        {field: 'warehousing_quantity', title: __('Warehousing_quantity'), operate:'BETWEEN'},
                        {field: 'no_quantity', title: __('No_quantity'), operate:'BETWEEN'},
                        {field: 'warehouse_name', title: __('仓库'), operate: 'LIKE'},
                        {field: 'shelves_name', title: __('库区'), operate: 'LIKE'},
                        {field: 'remark', title: __('Remark'), operate: 'LIKE'},
                        {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false,operate:false},
                        {field: 'status', title: '状态', searchList: {"2":'待质检',"1":'已质检',"0":"关闭"}, formatter: Table.api.formatter.normal},
                        // {field: 'operate', title: __('Operate'), table: table,
                        //     buttons: [
                        //         {name: 'detail', text: '详情', title: '详情', icon: 'fa fa-list', classname: 'btn btn-xs btn-primary btn-dialog',url:'inventory/procure/edit?flag=print&single=0',}
                        //     ],
                        //     events: Table.api.events.operate,
                        //     formatter:function (value, row, index) {
                        //         var that = $.extend({},this);
                        //         var table = $(this.table).clone(true);
                        //         //后端传之判断是否有编辑、删除操作权限
                        //         $(table).data('operate-edit',null);
                        //         $(table).data('operate-del',null);
                        //         that.table = table;
                        //         return Table.api.formatter.operate.call(that,value,row,index);
                        //     }
                        // }
                    ]
                ],
                queryParams: function (params) {
	                var filter = params.filter ? JSON.parse(params.filter) : {};
	                var op = params.op ? JSON.parse(params.op) : {};
	                
	                params.filter = JSON.stringify(filter);
	                params.op = JSON.stringify(op);
	                params.procure_type = 1
	                return params;
	            },
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
            $('#print-btn').click(function(){
                let list =  table.bootstrapTable('getSelections');
                if(list.length==0){
                    return Toastr.error("请先选择要打印的记录");   
                }
                let ids_arr = []
                let cBatch_arr = []
                var date = new Date();
                var today = formatDate(date);
                for(let i=0;i<list.length;i++){
                    ids_arr.push(list[i].inv_id)
                    if(!list[i].cBatch){
                        list[i].cBatch = today
                    }
                    cBatch_arr.push(list[i].cBatch)
                }
                Fast.api.open('information/inventory/print?inventory_id='+ids_arr.join(',')+'&cBatch='+cBatch_arr.join(','),'打印物料信息');
            })
            
            //入库分析清单打印
            $(document).on("click", ".btn-print", function (e, obj) {
            	let ids =  Controller.api.selectedids(table);
            	if(!ids.length){
            		Toastr.error("请选择要打印的入库分析清单");
            		return
            	}
            	let ids_arr = []
            	for(let i=0;i<ids.length;i++){
            		if(i>0&&ids[i].warehousing_code!=ids[i-1].warehousing_code){
            			Toastr.error("请选择同一张采购订单");
            			return 
            		}
            		ids_arr.push(ids[i].id)
            	}
            	Backend.api.open("inventory/procure/edit?flag=print&single=1&ids="+ids_arr.join(','),"入库任务分析打印") //,{area:["100%", "100%"]}
            })
        },
        recyclebin: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    'dragsort_url': ''
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: 'inventory/procure/recyclebin' + location.search,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {
                            field: 'deletetime',
                            title: __('Deletetime'),
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            formatter: Table.api.formatter.datetime
                        },
                        {
                            field: 'operate',
                            width: '140px',
                            title: __('Operate'),
                            table: table,
                            events: Table.api.events.operate,
                            buttons: [
                                {
                                    name: 'Restore',
                                    text: __('Restore'),
                                    classname: 'btn btn-xs btn-info btn-ajax btn-restoreit',
                                    icon: 'fa fa-rotate-left',
                                    url: 'inventory/procure/restore',
                                    refresh: true
                                },
                                {
                                    name: 'Destroy',
                                    text: __('Destroy'),
                                    classname: 'btn btn-xs btn-danger btn-ajax btn-destroyit',
                                    icon: 'fa fa-times',
                                    url: 'inventory/procure/destroy',
                                    refresh: true
                                }
                            ],
                            formatter: Table.api.formatter.operate
                        }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        add: function () {
            Controller.api.bindevent();
        },
        edit: function () {
        	$(document).on("click", ".btn-print", function(){
        		$(".widget-body").css("display",'none');
        	    window.print();
        	    $(".widget-body").css("display",'')
        	    Fast.api.close(); // 关闭弹窗
        	});
            // 为表格绑定事件
        	Controller.api.bindevent();
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            },
            selectedids: function (table, current) {
                var options = table.bootstrapTable('getOptions');
                //如果有设置翻页记忆模式
                if (!current && options.maintainSelected) {
                    return options.selectedIds;
                }
                return $.map(table.bootstrapTable('getSelections'), function (row) {
                    return row;
                });
            },
            events:{
                'change #c-warehouse_id':function(eom,value, row, index){
                     let new_row = {...row,...{warehouse_id:$(this).val()}}
                     //$("#table").bootstrapTable('updateRow',{index:index,row:new_row});
                },
                'click #c-warehouse_id':function(eom,value, row, index){
                    let that=this;
                    let html="";
                    if($(this).html()=="")
                    $.post('information/warehouse/index',{}, function(e){     
                        for(var i=0;i<e.total;i++){
                            html+='<option value='+e.rows[i].id+'>'+e.rows[i].name+'</option>'
                        }
                        $(that).html("");
                        $(that).append(html);
              });
              },
              'change #c-shelves_id':function(eom,value, row, index){
                  console.log(row);
              },
              'click #c-shelves_id':function(eom,value, row, index){
                let html="";
                let that=this;
                if($(this).html()=="")
                $.post('information/shelves/index',{}, function(e){     
                    for(var i=0;i<e.total;i++){
                        html+='<option value='+e.rows[i].id+' >'+e.rows[i].name+'</option>'
                    }
                    $(that).html("");
                    $(that).append(html);
          });
          }
                
            },
            formatter:{
                select:function(value, row, index){
                 let  html = '<select id="c-warehouse_id"  class="form-control"></select>';
                 return html; 
                },
                select_she:function(value, row, index){
                    let  html = '<select id="c-shelves_id"  class="form-control"></select>';
                    return html; 
                   }
            }
        }
    };
    return Controller;
});

//格式化日期：yyyy-MM-dd
function formatDate(date) {
    var myyear = date.getFullYear();
    var mymonth = date.getMonth() + 1;
    var myweekday = date.getDate();
 
    if (mymonth < 10) {
        mymonth = "0" + mymonth;
    }
    if (myweekday < 10) {
        myweekday = "0" + myweekday;
    }
    
    return myyear +""+  mymonth + "" + myweekday;//想要什么格式都可以随便自己拼
}